package com.old.nsi_class.api;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.old.model.Model;
import com.old.nsi_class.DB.Course_DB;
import com.old.nsi_class.model.Course_User_model;
import com.old.nsi_class.model.Course_model;
import com.old.user.User_DB;
import com.old.user.User_model;

@WebServlet("/Class_User_api")
public class Class_User_api extends HttpServlet{
	
	/**
	 * 生成序列化接口 
	 */
	private static final long serialVersionUID = -6822521399036215103L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		this.doPost(req, res);
	}
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String whereFrom = null;
		whereFrom = req.getParameter("whereFrom");
		
		
		/**
		 * 直播Class功能验证
		 */
		if(whereFrom.equals("login")) {
			//接受参数
			String name = req.getParameter("username");
			String pwd = req.getParameter("pwd");
			//实例化对象
			Model model=new Model();
            //默认值为-2 表示没有该用户
			int member_sign=-2;
			int UserVerifyCode=000000;
			String User_TureName="空";
			String User_Mail = null;
		   	//定义数字范围(正则表达式)
		   	Pattern pattern = Pattern.compile("[0-9]*"); 
		   	//传参
		    Matcher isNum = pattern.matcher(name);
		    //如果输入的不是数字就按照邮箱登陆
		    if(!isNum.matches()) {
	            //如果用户名,密码都通过，			
				if(model.checkUser(name, pwd)){									
	                //获取用户标志位
					member_sign=model.queryByName(name).getMember_sign();
					System.out.println("User_api:用户标志位："+member_sign);						
					UserVerifyCode=name.length()*member_sign+987654;
					User_TureName =model.queryByName(name).getUser_TureName();
	                //账号密码错误
				}else{
					//失败返回信息 
					System.out.println("User_api:"+name+"密码校验错误");
					UserVerifyCode=0;
					User_TureName="0";
				}
				//返回数据
				toResult(req, res, name, member_sign, UserVerifyCode, User_TureName);
		    //否则按照手机号登陆	
		    }else {
		    	//如果是手机号和密码都通过
		    	if(model.checkUserPhone(name,pwd)) {
		    		member_sign=model.queryByPhone(name).getMember_sign();
		    		System.out.println("User_api:用户标志位："+member_sign);
		    		UserVerifyCode=name.length()*member_sign+987654;
					User_TureName =model.queryByPhone(name).getUser_TureName();
					User_Mail = model.queryByPhone(name).getName();
		    	}else {
		    		System.out.println("User_api:"+name+"密码效验错误");
		    		UserVerifyCode=0;
					User_TureName="0";
					User_Mail="0";
		    	}
		    	//返回数据
				toResult(req, res, User_Mail, member_sign, UserVerifyCode, User_TureName);
		    }
		
			
		/**
		 * 	获取直播间地址
		 */
		}else if(whereFrom.equals("getLiveUrl")) {
			//接受用户参数
			String userid = req.getParameter("userid");
			String CourseId = req.getParameter("CourseId");
			String ts = Long.toString(System.currentTimeMillis());
			
//			直播间问题
			String SECRETKEY="null";
			switch (CourseId) {
//				case "10001":SECRETKEY="Attx35gs0G"; break;
//				case "10002":SECRETKEY="QqDEPC2RSC"; break;
//				case "10003":SECRETKEY="zGoTwgTiSi"; break;
//				case "10004":SECRETKEY="qMqRb8hzeN"; break;
//				case "10005":SECRETKEY="B5liKAFq1s"; break;
//				case "10006":SECRETKEY="oqmEYgls18"; break;
////				7 9两课互换-密匙未换
//				case "10007":SECRETKEY="8KmlfVr8HV"; break;
//				case "10008":SECRETKEY="ftCxgG510E"; break;
//				case "10009":SECRETKEY="6MffVIPKSi"; break;
//				case "10010":SECRETKEY="5Uzfcyvh9j"; break;
//				case "10011":SECRETKEY="QePHm4HhTa"; break;
//				case "10012":SECRETKEY="FkK1RtIgas"; break;
//				case "10013":SECRETKEY="eGPaR7ZSjf"; break;
//				case "10014":SECRETKEY="jFG6MQDdGF"; break;
//				case "10015":SECRETKEY="0L6vD2Nvr6"; break;

				case "20001":SECRETKEY="4jFdTVhUj4"; break;
				case "20002":SECRETKEY="rdsiFluHDQ"; break;
				case "20003":SECRETKEY="RHtH8NKucr"; break;
				case "20004":SECRETKEY="Attx35gs0G"; break;
				case "20005":SECRETKEY="QqDEPC2RSC"; break;
				case "20006":SECRETKEY="zGoTwgTiSi"; break;
				case "20007":SECRETKEY="qMqRb8hzeN"; break;
				case "20008":SECRETKEY="B5liKAFq1s"; break;
				case "20009":SECRETKEY="oqmEYgls18"; break;
				case "20010":SECRETKEY="8KmlfVr8HV"; break;
				case "20011":SECRETKEY="ftCxgG510E"; break;
				case "20012":SECRETKEY="6MffVIPKSi"; break;
				case "20013":SECRETKEY="5Uzfcyvh9j"; break;
				case "20014":SECRETKEY="QePHm4HhTa"; break;

				case "20015":SECRETKEY=""; break;

			default:
				break;
			}
					
			String strMD5 = SECRETKEY + userid + SECRETKEY + ts;
			String sign = null;
			
//			查询课程的直播地址
			String sql="SELECT * from nsi_course WHERE Id="+CourseId+";";
			List<Course_model> list = new ArrayList<Course_model>();
			list= Course_DB.CourseSearch(sql);
			String LiveUrl=list.get(0).getChannelName();
			
			try {
				//加密字符串
				sign = Class_User_api.md5Digest(strMD5);
			} catch (NoSuchAlgorithmException e) {
				System.out.println("加密失败...");
				e.printStackTrace();
			}
			String UrlMsg = "userid="+userid+"&ts="+ts+"&sign="+sign+"\"";
			String back="{\"msg\":\""+LiveUrl+"?"+UrlMsg+"}";
			
			System.out.println("getLiveUrl的SECRETKEY值:"+SECRETKEY);
			System.out.println("getLiveUrl的返回值：back："+back);
			
			res.setContentType("application/json;charset=UTF-8");  
			res.getWriter().write(back);
			
			
		/**
		 * 	用户购买课程，加入课程用户关联表
		 */
		}else if(whereFrom.equals("BuyClass")) {
			
			System.out.println("Class_User_api:WF=====BuyClass");
			String UserMail = req.getParameter("UserMail");
			String ClassId = req.getParameter("ClassId");			
			String sql="insert nsi_course_user (ClassId,UserMail) values ('"+ClassId+"','"+UserMail+"'); ";
			int i=Course_DB.insert02(sql);		
			String back="{\"msg\":"+i+"}";	
	    	String Callback = req.getParameter("Callback");//客户端请求参数
	    	res.setContentType("text/html;charset=UTF-8");
	    	res.getWriter().write(Callback+"("+back+")");    	

	   	
    	   /**
	     * 验证是否购买过课程	
	     */
		}else if("Verification".equals(whereFrom)) {
			System.out.println("Class_User_api:WF=====Verification");
			String UserMail = req.getParameter("UserMail");
			String ClassId = req.getParameter("ClassId");	
			String sql = "SELECT * FROM nsi_course_user WHERE ClassId='"+ClassId+"' and UserMail='"+UserMail+"';";
			int count = Course_DB.count(sql);
			if(count>=1) {
				String back="{\"msg\":1}";	
				res.setContentType("application/json;charset=UTF-8");  
				res.getWriter().write(back);
			}else {
				String back="{\"msg\":-1}";	
		    	res.setContentType("application/json;charset=UTF-8");  
				res.getWriter().write(back);
			}

	    
			
		/**
		 * 	批量插入用户课程，课程用户对应表
		 */
		}else if(whereFrom.equals("Course_User_Insert")) {
			System.out.println("Class_User_api:WF=====Course_User_Insert");
//			只传课程ID、则批量插入 该课程的对应表
//			传入课程Id、用户邮箱：为该用户加入该课程		
			String UserMail = req.getParameter("UserMail");
			String ClassId = req.getParameter("ClassId");
			int j=-1;
			//购买业务执行
			String sql03="select * from nsi_course_user where ClassId= '"+ClassId+"' AND UserMail='"+UserMail+"';";
			int count03 = Course_DB.count(sql03);
//				等于0 ，表示未购买过
			if(count03==0) {
				String sql02="insert nsi_course_user (ClassId,UserMail) values ('"+ClassId+"','"+UserMail+"'); ";
				j=Course_DB.insert02(sql02);
			}
			System.out.println("Course_User_Insert:单个插入"+ClassId+"-"+UserMail+"插入操作返回值："+j);	
			String back="{\"msg\":"+j+"}";	
	    	res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write(back);   
		
	    	
	    	/**
			 * 	批量插入用户课程，课程用户对应表
			 */
		}else if(whereFrom.equals("Course_User_BatchInsert")) {
			System.out.println("Class_User_api:WF=====Course_User_BatchInsert");
//			只传课程ID、则批量插入 该课程的对应表
//			传入课程Id、用户邮箱：为该用户加入该课程		
			String ClassId = req.getParameter("ClassId");
//			上一次课的ID
			int ClassIdInt=Integer.parseInt(ClassId)-1;
			int j=-1;
			
//			存在重复bug
//			1、遍历用户表
				String sql="select * from nsi_course_user WHERE ClassId='"+ClassIdInt+"';";
				List<Course_User_model> list = new ArrayList<Course_User_model>();
				list=Course_DB.CourseUserSearch(sql);
				for(int i=0;i<list.size();i++) {
					String UserMail=list.get(i).getUserMail();
					String sql02="insert nsi_course_user (ClassId,UserMail) values ('"+ClassId+"','"+UserMail+"'); ";
					j=Course_DB.insert02(sql02);
				}
									
			System.out.println("Course_User_BatchInsert:最终结果： "+j);		
			String back="{\"msg\":"+j+"}";	
	    	res.setContentType("application/json;charset=UTF-8");  
	    	res.getWriter().write(back); 	
	    	
	    	
//		返回Course_User表对应的详细信息     	
		}else if(whereFrom.equals("Course_UserInfo")){
			System.out.println("Class_User_api:WF=====Course_UserInfo");
//			1、获取用户名 2、查询该用户信息 
			String UserMail=req.getParameter("UserMail");
			String ClassId = req.getParameter("ClassId");
			
	    	String sql="SELECT * FROM nsi_user WHERE UserName='"+UserMail+"'";
	    	String sql02="SELECT * from nsi_course Where Id="+ClassId+" order by CourseRelease DESC;";
	    	List<User_model> list = new ArrayList<User_model>();
	    	list= User_DB.Search(sql);
	    	List<Course_model> list02 = new ArrayList<Course_model>();
	    	list02=Course_DB.CourseSearch(sql02);
	    	
	    	Gson gson = new Gson(); 
	    	String jsonList =gson.toJson(list);
	    	String jsonList02 =gson.toJson(list02);
			res.setContentType("application/json;charset=UTF-8");  		
			res.getWriter().write("{\"data\":"+jsonList+",\"data02\":"+jsonList02+"}");			
			
			
	    	
//		未接收到参数，返回错误代码 -3
		}else{
			System.out.println("Class_User_api WF参数错误，未执行");
			String back="{\"msg\":-3}";	
	    	String Callback = req.getParameter("Callback");//客户端请求参数
	    	res.setContentType("text/html;charset=UTF-8");
	    	res.getWriter().write(Callback+"("+back+")");
		}
	}

	
	
	
//	------------------------------返回结果 封装----------------------------------
	
	/**
	 * 返回结果
	 * @param req 接受参数
	 * @param res 响应参数
	 * @param name 
	 * @param member_sign
	 * @param UserVerifyCode
	 * @param User_TureName
	 * @throws IOException
	 */
	private void toResult(HttpServletRequest req, HttpServletResponse res, String name, int member_sign,
			int UserVerifyCode, String User_TureName) throws IOException {
		String back="{\"member_sign\":\""+member_sign+"\","
					+ "\"username\":\""+name+"\","
					+ "\"User_TureName\":\""+User_TureName+"\","
					+ "\"UserVerifyCode\":\""+UserVerifyCode+"\"}";
		String Callback = req.getParameter("Callback");//客户端请求参数	  	    	
		res.setContentType("text/html;charset=UTF-8");  
		res.getWriter().write(Callback+"("+back+")");
	}
	
	/**
	 * 加密方法
	 * @param strMD5 需要加密的字符串
	 * @return 加密后的字符串
	 * @throws NoSuchAlgorithmException 加密异常
	 */
	public static String md5Digest(String strMD5) throws NoSuchAlgorithmException {
		//引入MD5加密
		MessageDigest alg = MessageDigest.getInstance("MD5");
		//加密后的字符串
		alg.update(strMD5.getBytes());
		byte[] digest = alg.digest();
		String validateMD5 = byte2hex(digest);
		return validateMD5;
	}
	
    /*
     * 二进制转换为十六进制字符串
     * @param digest 二进制数组 @return 十六进制字符串
     */
    public static String byte2hex(byte[] digest) {
    	String hs = "";
		String stmp = "";
		for (int i = 0; i < digest.length; i++) {
			stmp = (Integer.toHexString(digest[i] & 0XFF));
		    if (stmp.length() == 1) {
		    	hs = hs + "0" + stmp;
		    }else {
		    	hs = hs + stmp;
		    }
		  }
		return hs;
    }

   
}
